/* *
* Promise.race是 JavaScript 中用于处理多个Promise的一个方法。它接受一个可迭代对象（通常是一个Promise数组）作为参数。
* 其核心行为是 “竞赛”，当传入的可迭代对象中的任意一个Promise被解决（fulfilled或者rejected）时，
* Promise.race返回的Promise就会立即采用这个最先被解决的Promise的状态和值。就好像一场赛跑比赛，只要有一个选手到达终点（被解决），比赛就结束
*
* 场景：超时控制、资源加载竞争场景（谁先出就用谁）
*
* */

function myPromiseRace(promises) {

   return new Promise((resolve, reject) => {
       if (promises === null || typeof promises[Symbol.iterator] !== 'function') {
           throw new Error("不可迭代")
       }
       if (promises.length === 0) return resolve([])
       promises.forEach(promise => {
           Promise.resolve(promise).then(res => resolve(res),err => reject(err))
       })
   })

}

const promise1 = new Promise((resolve, reject) => {
    setTimeout(() => resolve('Promise 1 resolved'), 4000);
});

const promise2 = new Promise((resolve, reject) => {
    setTimeout(() => resolve('Promise 2 resolved'), 3000);
});

const promise3 = new Promise((resolve, reject) => {
    setTimeout(() => resolve('Promise 3 resolved'), 2000);
});
const promise4 = new Promise((resolve, reject) => {
    setTimeout(() => reject('Promise 4 rejected'), 1000);
});
// 就看谁最先调用then的回调函数了 也就是看谁先执行resolve/reject
myPromiseRace([promise4, promise2, promise1, promise3])
    .then(result => console.log('Race resolved with:', result), error => console.log('Race rejected with:', error))
Promise.race([promise4, promise2, promise1, promise3])
    .then(result => console.log('Race resolved with:', result), error => console.log('Race rejected with:', error))
